﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DtoFw;
using Google.Protobuf.WellKnownTypes;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Service;
using Util;

namespace SceneEvidenceAPI.Controllers
{
    /// <summary>
    /// 首页
    /// </summary>
    [Route("api/home")]
    public class MainHomeController : BaseController
    {
        private readonly MainOrganService _organService;
        private readonly MainUserService _mainUser;
        public MainHomeController(MainOrganService organService, MainUserService mainUser)
        {
            this._organService = organService;
            this._mainUser = mainUser;
        }
        [AllowAnonymous]
        [HttpGet("queryorgan")]
        public BaseGenericResult<object> QueryOrgans(string latestTime,string timeStamp,string nonceStr,string signature)
        {
            var ret = Verify(latestTime,timeStamp, nonceStr, signature);
            if (ret.Success)
            {
                DateTime? latest = null;
                if (!string.IsNullOrEmpty(latestTime) && DateTime.TryParse(latestTime,out DateTime _dt))
                {
                    latest = _dt;
                }
                ret.Data = _organService.QueryAll(latest).Select(v => new
                {
                    v.Id,
                    v.Name,
                    v.SuperiorId,
                    v.ComNo,
                    v.Fax,
                    v.Tel,
                    v.Addrs,
                    v.ModifyerTime,
                    v.IsDeleted
                });
                return ret;
            }
            else
            {
                return ret;
            }
        }
        [AllowAnonymous]
        [HttpGet("queryuser")]
        public BaseGenericResult<object> QueryUsers(string latestTime, string timeStamp, string nonceStr, string signature)
        {
            var ret = Verify(latestTime, timeStamp, nonceStr, signature);
            if (ret.Success)
            {
                DateTime? latest = null;
                if (!string.IsNullOrEmpty(latestTime) && DateTime.TryParse(latestTime, out DateTime _dt))
                {
                    latest = _dt;
                }
                ret.Data = _mainUser.QueryAll(latest).Select(v => new
                {
                    v.Id,
                    v.Name,
                    v.NickName,
                    Sex = (v.Sex.HasValue ? (v.Sex.Value == 1 ? "男" : "女") : ""),
                    v.PoliceNo,
                    v.UserNo,
                    v.OrgId,
                    v.Phone,
                    v.Email,
                    v.RankName,
                    v.ModifyerTime,
                    v.IsDisable,
                    v.IsDeleted
                });
                return ret;
            }
            else
            {
                return ret;
            }
        }
        [AllowAnonymous]
        [HttpGet("logininfo")]
        public BaseGenericResult<object> LoginInfo(string edata)
        {
            var ret = new BaseGenericResult<object>()
            {
                Success = false,
                Code = DtoFw.Enum.EnumReturnCode.BusError
            };
            if (string.IsNullOrEmpty(edata))
            {
                ret.Msg = "参数不能为空";
                return ret;
            }
            edata = SecurityHelper.Decrypt(edata);
            if (string.IsNullOrEmpty(edata))
            {
                ret.Msg = "参数不能为空";
                return ret;
            }
            var lst = edata.Split('&');
            var userId = lst[0];
            var timeStamp = lst[1];
            if (!long.TryParse(timeStamp, out long sec))
            {
                ret.Msg = "timeStamp格式不正确";
                return ret;
            }
            var now = DateTime.Now;
            var date = DateTime.Parse("1970.1.1 08:00").AddMilliseconds(sec);
            if (Math.Abs(now.Subtract(date).TotalSeconds) > 120)
            {
                ret.Msg = "请求已失效";
                return ret;
            }
            ret.Msg = "成功";
            ret.Success = true;
            ret.Code = DtoFw.Enum.EnumReturnCode.Success;
            var v = _mainUser.Query(long.Parse(userId));
            ret.Data = new
            {
                v.Id,
                v.Name,
                v.NickName,
                Sex = (v.Sex.HasValue ? (v.Sex.Value == 1 ? "男" : "女") : ""),
                v.PoliceNo,
                v.UserNo,
                v.OrgId,
                v.Phone,
                v.Email,
                v.RankName,
                v.ModifyerTime,
                v.IsDisable,
                v.IsDeleted
            };
            return ret;
        }
        BaseGenericResult<object> Verify(string latestTime, string timeStamp, string nonceStr, string signature)
        {
            var ret = new BaseGenericResult<object>()
            {
                Success = false,
                Code = DtoFw.Enum.EnumReturnCode.BusError
            };
            if (string.IsNullOrEmpty(timeStamp) || string.IsNullOrEmpty(nonceStr) || string.IsNullOrEmpty(signature))
            {
                ret.Msg = "参数不能为空";
                return ret;
            }
            if (!long.TryParse(timeStamp, out long sec))
            {
                ret.Msg = "timeStamp格式不正确";
                return ret;
            }
            var now = DateTime.Now;
            var date = DateTime.Parse("1970.1.1 08:00").AddMilliseconds(sec);
            if (Math.Abs(now.Subtract(date).TotalSeconds) > 120)
            {
                ret.Msg = "请求已失效";
                return ret;
            }
            var md5 = Util.Md5Helper.Md5Encrypt($"latestTime={latestTime}&nonceStr={nonceStr}&timeStamp={timeStamp}dc0531b286437cfcdd36760d08c9f092");
            if (md5 != signature)
            {
                ret.Msg = "签名验证失败";
                return ret;
            }
            ret.Msg = "成功";
            ret.Success = true;
            ret.Code = DtoFw.Enum.EnumReturnCode.Success;
            return ret;
        }

    }
}
